﻿using System;
using System.IO;
using System.Text;
using MyBasicLib.IO;

namespace MyBasicLib.Utilities.Log
{
    public class FileLogger : ILogger
    {
        public FileLogger()
        { }
        public FileLogger(string relativeFilePath, LogLevel minLogLevel)
        {
            FilePath = relativeFilePath;
            MinLogLevel = minLogLevel;
        } 
        string logFilePath;
        public string FilePath
        {
            get
            {
                return logFilePath;
            }
            set
            {
                var relativeFilePath = value;
                relativeFilePath = relativeFilePath.Trim('/', '\\');
                logFilePath = Path.Combine(PathHelper.CurrentDirectory, relativeFilePath);
                logFilePath += "\\";
            }
        }
        public LogLevel MinLogLevel
        {
            get;
            set;
        }
        #region ILogger Members

        public void Info(string message)
        {
            if (ToLog(LogLevel.Info)) Log(LogLevel.Info, message);
        }

        public void Warning(string message)
        {
            if (ToLog(LogLevel.Warning)) Log(LogLevel.Warning, message);
        }

        public void Error(string message)
        {
            if (ToLog(LogLevel.Error)) Log(LogLevel.Error, message);
        }

        public void Info(Func<string> message)
        {
            if (ToLog(LogLevel.Info)) Log(LogLevel.Info, message());
        }

        public void Warning(Func<string> message)
        {
            if (ToLog(LogLevel.Warning)) Log(LogLevel.Warning, message());
        }

        public void Error(Func<string> message)
        {
            if (ToLog(LogLevel.Error)) Log(LogLevel.Error, message());
        }

        #endregion

        private bool ToLog(LogLevel level)
        {
            return level >= MinLogLevel;
        }

        private void Log(LogLevel level, string message)
        {
            if (ToLog(level))
            {
                try
                {
                    PathHelper.EnsureDirectoryExists(logFilePath);
                    string file = string.Format("{0}{1}_{2:yyyy-MM-dd}{3}", logFilePath, Environment.UserName,
                                                DateTime.Today, ".txt");
                    string content = string.Format("{0} {1:yyyy-MM-dd HH:mm:ss}{3}{2}{3}", level, DateTime.Now, message,
                                                   Environment.NewLine);
                    File.AppendAllText(file, content, Encoding.UTF8);
                }
                catch
                {
                }
            }
        }
    }
}